package warmachinesystem.presentation.editpart;

import org.eclipse.emf.common.notify.Adapter;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.Notifier;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.gef.editparts.AbstractTreeEditPart;

import warmachineroster.Roster;

public class WarmachineGameSystemAbstractTreeEditPart extends AbstractTreeEditPart 
	implements Adapter {

	private Roster roster;
	
	private Notifier target;


	public WarmachineGameSystemAbstractTreeEditPart(Object gs, Roster roster) {
		this.roster = roster;
		setModel(gs);
	}

	/**
	 * Upon activation, attach to the model element as a property change listener.
	 */
	public void activate() {
		if (!isActive()) {
			hookIntoModel(getRoster());
			super.activate();
		}
	}

	protected Roster getRoster() {
		return roster;
	}

	//I hook the roster to refresh the units I can add to the roster
	private void hookIntoModel(EObject model) {
		if(model != null) {
			model.eAdapters().add(this);
		}
	}

	private void unhookFromModel(EObject model) {
		if(model != null) {
			model.eAdapters().remove(this);
		}
	}

	/**
	 * Upon deactivation, detach from the model element as a property change listener.
	 */
	public void deactivate() {
		if (isActive()) {
			unhookFromModel(getRoster());
			super.deactivate();
		}
	}

	public void notifyChanged(Notification notification) {
		//Dato che tutti i modelli si agganciano al roster e che il "numero" di figli dell'albero non cambia
		//posso limitarmi a fare il refresh visuals
						refreshVisuals();
	}

	public Notifier getTarget() {
		return target;
	}

	public void setTarget(Notifier newTarget) {
		target = newTarget;
	}

	public boolean isAdapterForType(Object type) {
		return (getModel().getClass() == type)||(getRoster().getClass() == type);
	}

}
